import os

from flask import Blueprint, render_template, request, flash, redirect, url_for, g, jsonify
from app.auth.views.auth import login_required
from app.blog.models import Category, Post, Friend_post, Events_post
from RealProject import db, BASE_DIR
from .forms import CategoryCreateForm, PostForm, CreateUserForm, Friend_PostForm
from app.auth.models import User
from werkzeug.security import check_password_hash, generate_password_hash
from app.admin.utils import upload_file_path

bp = Blueprint('admin', __name__, url_prefix='/admin', static_folder='static', template_folder='templates')


@bp.route('/')
@login_required
def index():
    # 主页视图
    posts_num = len(Post.query.all())
    users_num = len(User.query.all())
    return render_template('admin/index.html', posts_num=posts_num, users_num=users_num)


@bp.route('/category')
@login_required
def category():
    # 查看分类
    page = request.args.get('page', 1, type=int)
    pagination = Category.query.order_by(-Category.add_date).paginate(page=page, per_page=10, error_out=False)
    category_list = pagination.items
    return render_template('admin/category.html', category_list=category_list, pagination=pagination)


@bp.route('/category/add', methods=['GET', 'POST'])
@login_required
def category_add():
    # 增加分类
    form = CategoryCreateForm()
    if form.validate_on_submit():
        category = Category(name=form.name.data, icon=form.icon.data)
        db.session.add(category)
        db.session.commit()
        flash(f'{form.name.data}分类添加成功')
        return redirect(url_for('admin.category'))
    return render_template('admin/category_form.html', form=form)


@bp.route('/category/edit/<int:cate_id>', methods=['GET', 'POST'])
@login_required
def category_edit(cate_id):
    # 编辑分类
    category = Category.query.get(cate_id)
    form = CategoryCreateForm(name=category.name, icon=category.icon)
    if form.validate_on_submit():
        category.name = form.name.data
        category.icon = form.icon.data
        db.session.add(category)
        db.session.commit()
        flash(f'{form.name.data}分类修改成功')
        return redirect(url_for('admin.category'))
    return render_template('admin/category_form.html', form=form)


@bp.route('/category/delete/<int:cate_id>', methods=['GET', 'POST'])
@login_required
def category_del(cate_id):
    # 删除分类
    category = Category.query.get(cate_id)
    if category:
        # 级联删除 
        Post.query.filter(Post.post_id == category.cate_id).delete()
        db.session.delete(category)
        db.session.commit()
        flash(f'{category.name}分类删除成功')
        return redirect(url_for('admin.category'))


@bp.route('/article')
@login_required
def article():
    # 查看文章列表
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.order_by(-Post.add_date).paginate(page=page, per_page=10, error_out=False)
    post_list = pagination.items
    return render_template('admin/article.html', post_list=post_list, pagination=pagination)


@bp.route('/article/add', methods=['GET', 'POST'])
@login_required
def article_add():
    # 增加文章
    form = PostForm()
    # 分类
    form.category_id.choices = [(v.cate_id, v.name) for v in Category.query.all()]

    if form.validate_on_submit():
        post = Post(
            user_id=g.user.user_id,
            title=form.title.data,
            desc=form.desc.data,
            has_type=form.has_type.data,
            category_id=int(form.category_id.data),  # 1对多保存
            content=form.content.data,
        )
        db.session.add(post)
        db.session.commit()
        flash(f'{form.title.data}文章添加成功')
        if g.user.is_super_user:
            return redirect(url_for('admin.article'))
        else:
            return redirect(url_for('auth.mypost'))
    return render_template('admin/article_form.html', form=form)


@bp.route('/add_friend', methods=['GET', 'POST'])
@login_required
def add_friend():
    cate_id = request.args.get('cate_id')
    # 增加文章
    form = Friend_PostForm()
    v = Category.query.filter(Category.cate_id == cate_id).first()
    form.category_id.choices = [(v.cate_id, v.name)]
    form.new_old.choices = [(1, '新朋友'), (2, '老朋友')]
    if form.validate_on_submit():
        post = Friend_post(
            user_id=g.user.user_id,
            title=form.title.data,
            desc=form.desc.data,
            has_type=form.has_type.data,
            category_id=cate_id,  # 1对多保存
            content=form.content.data,
            new_old=int(form.new_old.data)
        )
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('blog.cates_Friend', cate_id=cate_id))
    return render_template('admin/add_friend.html', form=form, cate_id=cate_id)


@bp.route('/add_event', methods=['GET', 'POST'])
@login_required
def add_event():
    cate_id = request.args.get('cate_id')
    # 增加文章
    form = PostForm()
    v = Category.query.filter(Category.cate_id == cate_id).first()
    form.category_id.choices = [(v.cate_id, v.name)]
    if form.validate_on_submit():
        post = Events_post(
            user_id=g.user.user_id,
            title=form.title.data,
            desc=form.desc.data,
            has_type=form.has_type.data,
            category_id=cate_id,  # 1对多保存
            content=form.content.data,
        )
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('blog.cates_Events', cate_id=cate_id))
    return render_template('admin/add_events.html', form=form, cate_id=cate_id)


@bp.route('/article/edit/<int:post_id>', methods=['GET', 'POST'])
@login_required
def article_edit(post_id):

    # 修改文章
    post = Post.query.get(post_id)
    form = PostForm(
        title=post.title, desc=post.desc,
        category_id=post.category.cate_id, has_type=post.has_type.value,
        content=post.content
    )

    form.category_id.choices = [(v.cate_id, v.name) for v in Category.query.first()]

    if form.validate_on_submit():
        post.title = form.title.data
        post.desc = form.desc.data
        post.has_type = form.has_type.data
        post.category_id = int(form.category_id.data)
        post.content = form.content.data
        db.session.add(post)
        db.session.commit()
        flash(f'{form.title.data}文章修改成功')
        if g.user.is_super_user:
            return redirect(url_for('admin.article'))
        else:
            return redirect(url_for('auth.mypost'))
    return render_template('admin/article_form.html', form=form)


@bp.route('/article/delete/<int:post_id>', methods=['GET', 'POST'])
@login_required
def article_del(post_id):
    # 删除文章
    cate_id = request.args.get('cate_id')
    if cate_id == '3':
        post = Events_post.query.get(post_id)
        if post:
            db.session.delete(post)
            db.session.commit()
    elif cate_id == '2':
        post = Friend_post.query.get(post_id)
        if post:
            db.session.delete(post)
            db.session.commit()
    # 如添加其他分类，按照上面的，加上分类的cate_id
    return redirect(url_for('blog.index'))


@bp.route('/user')
@login_required
def user():
    # 查看文章列表
    page = request.args.get('page', 1, type=int)
    pagination = User.query.order_by(-User.add_date).paginate(page=page, per_page=10, error_out=False)
    user_list = pagination.items
    return render_template('admin/user.html', user_list=user_list, pagination=pagination)


@bp.route('/user/add', methods=['GET', 'POST'])
@login_required
def user_add():
    # 添加用户
    # https://flask-wtf.readthedocs.io/en/1.0.x/form/#file-uploads  
    form = CreateUserForm()
    if form.validate_on_submit():
        f = form.avatar.data
        # 判断是否有头像（因为定义数据库时头像可为空）
        if f:
            avatar_path, filename = upload_file_path('avatar', f)
            f.save(avatar_path)
            user = User(
                username=form.username.data,
                email=form.email.data,
                password=generate_password_hash(form.password.data),
                avatar=f'avatar/{filename}',
                is_super_user=form.is_super_user.data,
                is_active=form.is_active.data,
                is_staff=form.is_staff.data
            )
        else:
            user = User(
                username=form.username.data,
                email=form.email.data,
                password=generate_password_hash(form.password.data),
                avatar=None,
                is_super_user=form.is_super_user.data,
                is_active=form.is_active.data,
                is_staff=form.is_staff.data
            )
        db.session.add(user)
        db.session.commit()
        flash(f'{form.username.data}用户添加成功')
        return redirect(url_for('admin.user'))
    return render_template('admin/user_form.html', form=form)


@bp.route('/user/edit/<int:user_id>', methods=['GET', 'POST'])
@login_required
def user_edit(user_id):
    # 修改用户信息
    user = User.query.get(user_id)

    from .utils import upload_file_path
    form = CreateUserForm(
        username=user.username,
        email=user.email,
        password=user.password,
        avatar=user.avatar,
        is_super_user=user.is_super_user,
        is_active=user.is_active,
        is_staff=user.is_staff
    )
    form.password.default = f'{user.password}'
    print(form.validate_on_submit())
    if form.validate_on_submit():
        user.username = form.username.data
        if not form.password.data:
            user.password = user.password
        else:
            user.password = generate_password_hash(form.password.data)
        if not form.email.data:
            user.email = user.email
        else:
            user.email = form.email.data
        f = form.avatar.data
        if user.avatar == f:
            user.avatar = user.avatar
        else:
            avatar_path, filename = upload_file_path('avatar', f)
            f.save(avatar_path)
            user.avatar = f'avatar/{filename}'
        user.is_super_user = form.is_super_user.data
        user.is_active = form.is_active.data
        user.is_staff = form.is_staff.data
        db.session.add(user)
        db.session.commit()
        flash(f'{user.username}修改成功')
        return redirect(url_for('admin.user'))
    return render_template('admin/user_form.html', form=form, user=user)


@bp.route('/user/del/<int:user_id>', methods=['GET', 'POST'])
@login_required
def user_del(user_id):
    # 删除用户
    user = User.query.get(user_id)
    if user:
        db.session.delete(user)
        db.session.commit()
        flash(f'{user.username}删除成功')
        return redirect(url_for('admin.user'))


@bp.route('/upload', methods=['POST'])
@login_required
def upload():
    # 上传图片
    if request.method == 'POST':
        f = request.files.get('upload')
        file_size = len(f.read())
        f.seek(0)  # reset cursor position to beginning of file

        if file_size > 2048000:  # 限制上传大小为2M
            return {
                'code': 'err',
                'message': '文件超过限制2048000字节',
            }
        upload_path, filename = upload_file_path('upload', f)
        f.save(upload_path)
        return {
            'code': 'ok',
            'url': f'/admin/static/upload/{filename}'
        }


